package com.yya.ratelimiter.utils;

import cn.hutool.extra.servlet.ServletUtil;
import com.yya.ratelimiter.annotation.RateLimit;
import com.yya.ratelimiter.enums.LimitType;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Autor: yuanyongan
 * @Description:
 * @Date 2023/1/28 17:52
 */
public class RedisUtils {

    @Resource
    static RedisTemplate<String, Object> redisTemplate;

    /**
     * redis中是否包含某个key
     */
    public static boolean haxKey(String key){
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 获取value值
     */
    public static Object get(String key){
        return  redisTemplate.opsForValue().get(key);
    }

    /**
     * 存放数据
     */
    public static void set(String key, Object val){
        redisTemplate.opsForValue().set(key, val);
    }

    /**
     * redis中的key两种格式
     * 1、rate_limit:com.xxx.controller.xxxController-methodName  表示对接口进行限流
     * 2、rate_limit:127.0.0.1-com.xxx.controller.xxxController-methodName 表示针对ip进行限流
     * @param rateLimit 限流注解参数
     * @param methodSignature 切片参数，本项目限流都时基于切片实现的
     * @return
     */
    public static String getRateLimitKey(RateLimit rateLimit, MethodSignature methodSignature) {
        StringBuilder key = new StringBuilder(rateLimit.key());
        if (rateLimit.limitType() == LimitType.IP){
            // 获取客户端ip
            String clientIp = ServletUtil.getClientIP(((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest());
            key.append(clientIp).append("-");
        }
        Method method = methodSignature.getMethod();
        // 获取类名
        String className = method.getDeclaringClass().getName();
        // 获取方法名
        String methodName = method.getName();

        key.append(className)
                .append("-")
                .append(methodName);
        System.out.println("全类名+方法名" + className + "-" + methodName);
        return key.toString();
    }
}

